package cn.znzz.cjm.filter;

import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SmsCodeFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //获取url  判断是否是验证码登录的请求
        String uri = httpServletRequest.getRequestURI();
        if("/smslogin".equals(uri)){
            //如果是  则获取请求中的参数  以及session中的验证码信息进行比对
            String phone = httpServletRequest.getParameter("phone");
            String code = httpServletRequest.getParameter("code");
            //获取session中存储的code
            String scode = (String)httpServletRequest.getSession().getAttribute("smscode::" + phone);
            //比对成功 放行  比对失败  告知验证码输入错误
            if(code!=null&& !code.equalsIgnoreCase(scode)){
                throw new RuntimeException("验证码输入错误!");
            }
        }
        //其它的请求放行
        filterChain.doFilter(httpServletRequest,httpServletResponse);

    }
}